<template>
    <div class="page-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>用户列表</span>
                    <el-button type="primary" @click="openCreateDialog">创建新用户</el-button>
                </div>
            </template>
            <el-table :data="users" v-loading="loading" style="width: 100%">
                <el-table-column prop="id" label="ID" width="180"></el-table-column>
                <el-table-column prop="username" label="用户名" width="180"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="realName" label="真实姓名"></el-table-column>
                <el-table-column prop="gender" label="性别"></el-table-column>
                <el-table-column prop="age" label="年龄"></el-table-column>
                <el-table-column prop="roles" label="角色">
                    <template #default="scope">
                        <el-tag v-for="role in scope.row.roles" :key="role" style="margin-right: 5px;">{{ role
                            }}</el-tag>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <UserForm v-model:visible="formDialogVisible" :user-data="selectedUser" @saved="handleSaveUser" />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { createUser, getAllUsers } from '@/api/userApi'; // 导入 getAllUsers
import UserForm from '@/components/user/UserForm.vue';

const users = ref([]);
const loading = ref(false);
const formDialogVisible = ref(false);
const selectedUser = ref(null);

// 更新 fetchUsers 方法以调用API
const fetchUsers = async () => {
    loading.value = true;
    try {
        const response = await getAllUsers();
        users.value = response.data;
    } catch (error) {
        ElMessage.error('获取用户列表失败');
        console.error(error);
    } finally {
        loading.value = false;
    }
};

const openCreateDialog = () => {
    selectedUser.value = null;
    formDialogVisible.value = true;
};

const handleSaveUser = async (data) => {
    try {
        await createUser(data);
        ElMessage.success('用户创建成功');
        formDialogVisible.value = false;
        fetchUsers(); // 创建成功后刷新列表
    } catch (error) {
        const errorMessage = error.response?.data?.message || error.message;
        ElMessage.error(`保存失败: ${errorMessage}`);
    }
};

onMounted(fetchUsers);
</script>

<style scoped>
.page-container {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>